home *** CD-ROM | disk | FTP | other *** search
/ BMUG PD-ROM BV3 / BMUG PD-ROM Version BV3 (CDRM1097900).iso / Programming / Programming Languages / Pocket Forth 6 / Documents / Manual(part2) < prev   
Encoding:
Text File  |  1992-05-07  |  31.1 KB  |  470 lines  |  [TEXT/ttxt]

  1. (This is part 2 of the Pocket Forth version 0.6 manual)
  2. Toolbox
  3.  
  4. The Macintosh toolbox is a collection of hundreds of routines within the ROM and System file that create the distinctive interface present in most programs. Pocket Forth encourages the use of toolbox routines.
  5.  
  6. Toolbox routines are called by executing a 16 bit instruction called a trap word. Each routine has its own trap word that executes and returns as if it had been called as a subroutine. Compile trap words inline into Pocket Forth code.
  7.  
  8. A word ",$" (pronounced "comma hex") compiles a 16 bit hexadecimal number into the dictionary from the input stream. If the token after "comma hex" is not a hex number, a number conversion error is signaled. Use "comma hex" to compile trap words.
  9.  
  10. Most toolbox arguments are passed on the system stack. Because Pocket Forth's return stack is the system stack, return stack words can be used to setup for a toolbox call. The words ">r" and "2>r" move 16 and 32 bit values to the return stack. "R>" and "2r>" move 16 and 32 bit numbers from the return stack to the parameter stack. The word "a>r" performs a double duty: it converts a relative address on the stack to an absolute address which it pushes to the return stack.
  11.  
  12. To call a toolbox routine, setup the system stack with "a>r", ">r" and "2>r". If the toolbox call is a function, push a zero (single or double, as appropriate) to the return stack ahead of any arguments. Then compile the trap word with "comma-hex". Get function results with "r>" or "2r>". Examples of toolbox calls are in the example programs and figure 6, below.
  13.  
  14. The operating system keeps information for its use in low memory global variables. These globals can be accessed using absolute addressing with the words "l@" and "dl@". See the definition of "ticks" in figure 6.
  15.  
  16. Machine Language
  17.  
  18. Machine code can be mixed with Forth code in definitions. Insert it as hex data directly with the word "comma hex". Be sure that all words execute correctly and end with an RTS instruction or JMPs into another word's code field.
  19.  
  20. Respect the contents of most of the 680x0's registers. Save and restore registers that are used by Pocket Forth before changing them with machine code. The following table describes the register use:
  21.  
  22.         Register           Comments
  23.         D0-D1/A0-A1   Used and changed by many words; use freely
  24.         D2-D5               Preserved by all words; restore if used
  25.         D6.W                 Name address of the last definition (see "latest")
  26.         D7.W                 Input character counter
  27.         A2 (DP)             Start of free memory absolute address (see "here")
  28.         A3 (BP)             Base absolute address (see ">rel" and ">abs")
  29.         A4 (IS)              The input stream pointer absolute address
  30.         A5                     Macintosh operating system use
  31.         A6 (PS)             The parameter stack pointer absolute address
  32.         A7 (RS)             The return (and system) stack absolute address
  33.  
  34. The word "mon" executes the trap word _Debugger. If a debugger, such as TMON or MacsBug is installed, it is engaged, otherwise, the system bomb window appears. If it does, click the "Continue" (or "Resume") button to quit the application.
  35.  
  36. Here are examples of toolbox calls, system global variables and machine language:
  37.  
  38. : 0>R ( return stack: -- 0 ) ( push a zero to the return stack )
  39.     ,$ 4267 ; MACRO  ( clr -[rs] )
  40. : RANDOM ( -- u ) ( u is a random number, 0 to 65535 )
  41.     0>r ,$ A861  r> ;  ( _Random )
  42. : TICKS ( -- d ) ( double number = ticks since startup )
  43.     362 0 dl@ ;  ( fetch double from absolute address 362 )
  44. : CLS ( -- ) ( clear the window, leaving the cursor alone )
  45.     4 +md a>r ,$ A8A3 ;  ( _EraseRect the window content rect )
  46.  
  47. And a memory diagram for these words:
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59. figure 6
  60.  
  61. Events
  62.  
  63. Macintosh programs interact with users and other programs by means of 'events'. For example, clicking on a partially hidden window generates mouse down, mouse up, activate, deactivate and update events in order to bring the window to the front. Pocket Forth has default event handlers, so deal only with those that are pertinent.
  64.  
  65. The (relative) addresses of the event handlers are kept in a large table of unnamed variables. The addresses of the variables are calculated with the word "+md", which adds the address of the table to an offset. Some of the variables in the table hold other important data instead of handlers. You can customize Pocket Forth by changing the value of these variables.
  66.  
  67. Here is a list of the available variables. The left column's variables contain the addresses of routines. The right column contains handles, pointers, flags and other data.
  68.  
  69. Handler routines:    Offset            Other data:          Offset
  70.     Activate window    12              Window Pointer          0
  71.     Update window       14              WRect, pixels             4
  72.     Button down           16              WSize, pixels              8
  73.     Idle                        20               Menus list                18
  74.     Close                      22              Screen echo flag       28
  75.     Version                  24               AppleMenuHandle      30
  76.     Start up                  26              File Menu Handle       34
  77.     Event routines:     116               Edit Menu Handle       38
  78.         (Button down)   118              File stack                  42
  79.         (Button up)       120               Event record            148
  80.         (Key down)        122                  What event          148
  81.         (Key up)            124                   Message              150
  82.         (AutoKey)          126                  When                   154
  83.         (Update)            128                  Where                  158
  84.         (Disk inserted)  130                  Modify                 162
  85.         (Activate)         132               Selected window    164
  86.         (Apple Event)    136               Multitasking flag    186
  87.         (Multitask)        146              Apple Event list      188
  88.     Clicks:                   168              Key pressed flag     192
  89.         inDeskRgn          168              Quit selected flag   194
  90.         inMenuRgn          170              Open ready flag       196
  91.         inSystemRgn      172              Apple Event reply    198
  92.         inContentRgn      174             Apple Event record  202
  93.         inDragRgn           176
  94.         inGrowRgn          178
  95.         inCloseRgn         180
  96.         inZoomIn            182
  97.         inZoomOut          184
  98.     Apple Event error   190
  99.  
  100. Routines:
  101.  
  102. • Activate expects a flag on the stack, true for window on, false for window off. The default handler is the word "drop". Substitute handler should also take a number off the stack.
  103.  
  104. • Update draws invalidated portions of the window if automatically invalidated by uncovering it or explicitly invalidated by a program. The default handler draws an underscore at the current text cursor position, and has no stack effect.
  105.  
  106. • Button executes when the mouse button is pressed inside the window. The word "beep" is the default handler. Handlers can make use of the words "@mouse" and "?button" to create more complex mouse button actions. The button handler has no stack effect.
  107.  
  108. • Idle is executed as often as possible, at least every 30th of a second. The default Idle handler does nothing, however, the idle routine is used by some Apple Events.
  109.  
  110. • Close executes in response to a click in the window's close box. The default handler executes "bye" which quits Pocket Forth.
  111.  
  112. • Version is a handler that identifies the version of the program running. The default handler displays the About… box from the Apple menu.
  113.  
  114. • Start up is executed when the program starts, after the window has been drawn, and all the registers are set up.
  115.  
  116. • Events is a list of first line handlers for the first 15 event types. These handlers do the behind the scene housekeeping for Pocket Forth. They execute the handlers described above and do not normally need to be modified. Apple events are mapped onto event number 10, the defunct network event.
  117.  
  118. • Clicks is a list of the various window part handlers. They handle desktop, menubar, desk accessory, window content region, drag region, grow box, close box, zoom in and zoom out region clicks. Modify these handlers to change the way the Pocket Forth window responds to mouse clicks in regions other than the content region.
  119.  
  120. • Apple Event error is executed if the result code of AEProcessAppleEvent is not zero. This allows events other than Apple Events to be handled. See the Apple Event section.
  121.  
  122. Data:
  123.  
  124. • Window contains a pointer to Pocket Forth's window. Get the window pointer with "0 +md 2@".
  125.  
  126. • WRect is the content rect of the window in local coordinates and WSize is the last four bytes of the rect, the width and height of the window. The values in wrect are used by "cr" and "page" and other routines.
  127.  
  128. • Menus is a variable that holds the relative address of a list of menu lists. See the menu section for an explanation.
  129.  
  130. • Screen echo is a variable that contains a flag. If the flag is true then text is printed when pasting or loading. If it's false then printing isn't done and loading (or pasting) is much faster. If the source code contains errors however, you will not be able to see where the error occurred.
  131.  
  132. • Apple Menu Handle, File Menu Handle and Edit Menu Handle are double variables that hold menu handles for the three built in menus.
  133.  
  134. • File stack is the memory to implement the stacks required to allow programs to load other programs. See the source code to discover the inner workings of the file stack.
  135.  
  136. • Event record holds the event record data. This is the record used by the main event loop. Since the system puts necessary data here, you should not modify these variables. Your event handlers should, however, test them.
  137.  
  138. • Selected window holds a temporary window pointer. Update and other routines use this variable, so it should not be changed.
  139.  
  140. • Multitasking flag contains true (-1) if a multitasking operating system such as System 7 or MultiFinder is in effect. A true flag indicates that trap WaitNextEvent is available and will retrieve events, if the flag is false, GetNextEvent is used instead.
  141.  
  142. • Apple Event list is a linked list of relative address pointers to the handlers for each apple event supported. The format of the list is:  d.class d.message handler next.entry. The list is terminated with a zero for the next.entry field. Refer to the Apple Events section.
  143.  
  144. • Key pressed flag is used by the event loop. You should use the words "key" or "?terminal" to determine if a key is pressed.
  145.  
  146. • When the quit flag is set to any non zero value, the event loop exits Pocket Forth. Use the word "bye" to accomplish this.
  147.  
  148. • Open ready is true if a file is ready to be opened. The filename should be at 'pad' and a working directory number on the stack. This variable is used by "open", the 'odoc' handler and opening from the menu, but not by "-->".
  149.  
  150. • AEReply holds the handle to the reply Apple Event record, an empty apple event that is returned to the sending application. See the Apple Events section.
  151.  
  152. • AEEventRecord contains the handle to the current Apple Event data record. See the Apple Events section.
  153.  
  154. As mentioned above, none of these names are in the dictionary, but they can be defined as constants. Here are examples of the use of these variables:
  155.  
  156.     12 +md constant ACTIVATE
  157.     14 +md constant UPDATE
  158.     16 +md constant BUTTON
  159.     24 +md constant VERSION
  160.  
  161.     : MYACT ( flag -- ) IF ." Hello again!" cr THEN ;  ( type the string )
  162.     : MYUPD ( -- ) 4 0 DO 8 emit LOOP .ok  ( back up and issue prompt )
  163.          [ update @ compile ] ;  ( call the original update handler )
  164.     : MYBUT ( -- ) version @ execute ;  ( show version )
  165.  
  166.     ' myact activate !  ( set activate to address of "myact" )
  167.     ' myupd update !  ( set 'update' to address of "myupd" )
  168.     ' mybut button !  ( set 'button' to address of "mybut" )
  169.  
  170. Now try clicking on the window, hiding the window behind others, and re-selecting it.
  171.  
  172. More Variables
  173.  
  174. Other variables exist in the Pocket Forth dictionary, for use by the interpreter and other internal parts of the Pocket Forth system. These variables can also be used to patch Pocket Forth's actions. Unlike Forth's user variables, these are unnamed.
  175.  
  176. Here is a list of the 'user' variables, the offsets are bytes from "tib".
  177.  
  178.     Name     Offset  Description
  179.     TermBuf     0     terminal input buffer
  180.     StackSize 82    the size of the parameter stack, in bytes
  181.     IntA7        84     initial value of the system's stack pointer
  182.     Rzero        88     address of the bottom of the return stack
  183.     Szero        92     address of the bottom of the parameter stack
  184.     Form         96     decform record for floating point numbers
  185.     Expand    100     address of 'grow' routine in the CODE 1 resource
  186.     FreePt    104     relative address of the initial end of the dictionary
  187.     FreeSz    106     amount of free space at startup
  188.     DictPt    108     name address of the last word in the dictionary
  189.     NBase     110     value of the current number base at startup
  190.     Held       112     address for the next character in a numeral
  191.     DoesAdr 114     parameter from a created word for "does>"
  192.     fcolon    118     flag indicating the interpreter state (see "cstate")
  193.     fimmed  119     flag indicating an immediate word
  194.     fneg       120     flag indicating a negative number
  195.     fint        121     flag indicating input source (see "cblk")
  196.     fmacro   122     flag indicating macro compiling mode
  197.     fbit5      123     reserved flag
  198.  
  199.  
  200. Menus
  201.  
  202. Menus can be created and changed. Three menus are already setup, Apple, File and Edit. You can add your own menus. Each menu (except the Apple Menu) consists of four parts:  1) A menu ID number, 2) a menu handle, 3) a menu handler list with an entry for each item in the menu and 4) a MENU resource. The menu resource is optional, as you may define menus from strings as well. MENU resources are much easier. See the Window&Menu example file.
  203.  
  204. Menu ID numbers apply to all of the application's menus. Menus are numbered 2 for the File menu and 3 for the Edit menu. Give new menus a number of 4 and higher if any are added. Handles for the existing menus are in the unnamed variables as shown in the table.
  205.  
  206. The order in the list of menu item handlers corresponds to the appearance of the items in the menu. The addresses of the menu handler lists from each menu (except the Apple menu) are kept in a list that looks like the menubar. This list of menu lists is pointed to by the Menus list unnamed variable (18 +md). Perhaps this picture of the menu handlers and pointers will clear things up:
  207.  
  208.  
  209.  
  210.  
  211.  
  212.  
  213.  
  214.  
  215.  
  216.  
  217.  
  218.  
  219.  
  220.  
  221.  
  222.  
  223. figure 7
  224.  
  225. The Apple menu is handled separately because the only changeable item is About… which can be accessed via the Version unnamed variable.
  226.  
  227. To alter an item's handler, change the value of the handler in the menu's list to point to the word you want to run instead. To change an entire menu, change its address in the list of menus to point to a new list. This example sets the handler of the Clear item of the Edit menu to a word to clear the screen:
  228.  
  229.     ( Paste this example into Pocket Forth to try it out. )
  230.     18 +md @                          ( get the contents of menus list variable )
  231.     2+ @  constant EMLIST      ( address of the edit menu list )
  232.     : CLEAR ( -- ) page quit ;   ( clear screen and reset interpreter )
  233.     ' clear  emlist 5 2 * +  !    ( set item 5 {clear} to "clear" )
  234.  
  235. The menus included with Pocket Forth contain commands that facilitate interactive program development. The menu commands are:
  236.  
  237. Apple Menu
  238.  
  239.   About Pocket Forth ... runs the handler routine whose address is kept in the variable at 24 +md. The default handler displays an alert box.
  240.  
  241.   Desk accessories or Apple Menu Folder contents are displayed below the About item.
  242.  
  243. File Menu
  244.  
  245.   Open ... presents a dialog box to choose a file to be opened. The chosen file is then loaded.
  246.  
  247.   Save Dictionary ... presents a dialog asking you to confirm your choice. It does this because saving the dictionary cannot be undone. The dictionary is saved if you confirm the choice.
  248.  
  249.   Debugger ... enters a machine language monitor by executing the word "mon". You must have a monitor program, such as TMON or MacsBug installed or the program will crash.
  250.  
  251.   Print ... does nothing useful (it beeps).
  252.  
  253.   Quit executes "bye".
  254.  
  255. Edit Menu
  256.  
  257.   Undo, Cut, Copy and Clear do nothing except beep. They are provided to support desk accessories. See the example above to add a function to the Clear item.
  258.  
  259.   Paste interprets the text on the clipboard.
  260.  
  261.  
  262. Resources
  263.  
  264. Pocket Forth is entirely made out of resources. Here is a list of all of the resources in Pocket Forth:
  265.  
  266.         TYPE       ID       bytes
  267.         actb      257        48        about alert color table
  268.         actb      258        48        red alert color table
  269.         ALRT     257        14        about alert
  270.         ALRT     258        14        red (memory low) alert
  271.         ALRT     259        14        save alert
  272.         BNDL     128        36        finder icon bundle
  273.         CODE     0            24        launching code
  274.         CODE     1          182        more launching code
  275.         DICT      257    6468       dictionary code
  276.         DITL      257        50       about alert items list
  277.         DITL      258        90       red alert items list
  278.         DITL      259      154       save alert items list
  279.         FREF     128           7       finder reference for Pocket Forth
  280.         FREF     129           7       finder reference for text files
  281.         hdlg     257          50       about alert help balloon *
  282.         hdlg     259          82       save alert help balloon *
  283.         hfdr     -5696      32       finder icon help balloon *
  284.         hmnu    1             40       apple menu help balloon *
  285.         hmnu    2           148       file menu help balloon *
  286.         hmnu    3           140       edit menu help balloon *
  287.         hrct      128        32        window help balloon rect definition *
  288.         hwin     128        30        window help balloon *
  289.         icl4      128       512      16 color icon *
  290.         icl8      128     1024       256 color icon *
  291.         ICN#     128       256       black and white icon
  292.         ics#     128         64       small black and white icon *
  293.         ics4     128       128       small 16 color icon *
  294.         ics8     128       256       small 256 color icon *
  295.         MENU    1             48       apple menu
  296.         MENU    2           104       file menu
  297.         MENU    3             72       edit menu
  298.         p4TH    0              36      signature and string for Get Info
  299.         PICT    128        354       for the about dialog
  300.         SIZE     1              10      multitasking and System 7 info
  301.         STR#    1          2142      help balloon text *
  302.         WIND    128          32      the main window
  303.         * used by System 7 only
  304.  
  305. To use resources in a program, create and install them into a copy of Pocket Forth. Use ResEdit or an equivalent program to do the resource surgery. The Window&Menu example shows a method for creating resources on the fly.
  306.  
  307. The DICT resource of Pocket Forth contains the dictionary code and data. A resource was used for the dictionary because of the ease in saving and modifying the data within it.
  308.  
  309.  
  310. Floating Point Numbers
  311.  
  312. Pocket Forth can recognize and manipulate floating point numbers. While this is not a standard Forth feature, the language is well served by this implementation (14), especially if your Macintosh has floating point hardware. The floating point routines will run on any Macintosh.
  313.  
  314. Floating point numbers are implemented using the SANE software built into every Macintosh. SANE routines are fast and accurate. An available floating point chip is used by SANE automatically. This means, programs will benefit from its inclusion without needing specialized code.
  315.  
  316. A floating point number occupies 10 bytes in the following format:
  317.  
  318.  
  319.  
  320.  
  321.  
  322. figure 8
  323.  
  324. Indicate that a token is a floating point number by using only the characters 0-9, a decimal point, a plus or minus sign or the letter 'e'. The translator routine (part of SANE), is quite lenient, however the token must be a recognizable decimal or scientific notation number, ±INF or a NAN code as described by the Apple Numerics Manual (11). Examples of valid floating point numbers are:  3.1415926  78.  0.0000012  6.626E-34  6.02e23 .
  325.  
  326. SANE extended floating point numbers are 80 bits long, so they occupy 10 bytes in memory, or 5 cells on the stack. Illustrate this by typing "1.0 . . . . . ".
  327.  
  328. Words for working with floating point numbers are included. Many of these words are similar to integer words prefixed by 'f'. Words to manipulate floating point numbers on the stack ("fdrop", "fdup", "fswap", "fpick", "fpack" and "froll") and in memory ("f@", "f!", "fliteral", "f,", "fconstant" and "fvariable"), output them ("fix", "sci" and "f.") and convert them ("f>d", "d>f" and "fnumber") are all provided.
  329.  
  330. The sixteen math words make up the rest of the floating point suite. They are "f+", "f-", "f*", "f/", "frem", "f^", "fint", "fabs", "fsqrt", "fsin", "fcos", "ftan", "fexp", "fln" and "fcompare". The SANE financial functions are not included, but can be defined if needed. Refer to the glossary and source code for more information.
  331.  
  332. Here is an example that calculates the area of a circle of a given diameter:
  333.     : ACIRCLE ( f.diameter -- f.area )
  334.         2. f/                        ( calculate the radius )
  335.         fdup f*                    ( square it )
  336.         3.1415926 f* ;        ( multiply it by pi )
  337.  
  338.  
  339. Apple Events
  340.  
  341. Apple Events are fully supported. The four required events, 'oapp', 'odoc', 'pdoc' and 'quit' are predefined and installed at startup time. Your program may define additional event handlers and add them to the list to be installed the next time Pocket Forth is started.
  342.  
  343. To define an Apple Event, first put the event type and the event class double numbers on the stack, with ",s". Then use "ae:" and ";ae" to begin and end the definition. Write a procedure between them for the event handler. This process will attach the new definition to the tail of the Apple Events list. The defining word "ae:" handles the management of the Apple Event list so you do not need to deal with it.
  344.  
  345. Unlike the menu list, entries in the Apple Events list are installed into the system when the program starts up, and cannot be modified dynamically by your program. To install a new Apple Event, define the event then "save" the dictionary. (Be sure to use a copy of Pocket Forth!) Quit, then relaunch Pocket Forth and the new event handler is automatically installed.
  346.  
  347. When Pocket Forth receives an Apple Event, the AppleEvent and the Reply record addresses (absolute) are placed in the variables at "202 +md" and "198 +md". These addresses are used to extract information from, and respond to Apple Events. (10,13)
  348.  
  349. To see how this is done, check out the AppleEvents file and the HyperCard stack, AETest. This combination allows a line of code to be sent from HyperCard to Pocket Forth using the 'do script' event.
  350.  
  351. Here is an even simpler example. Make a copy of Pocket Forth and paste this in:
  352.  
  353.     : whide ( -- ) 0 +md 2@ 2>r ,$ A916 ;  ( _HideWindow )
  354.     ,s clos ,s aevt  ae:  whide  ;ae  ( define the 'clos' handler )
  355.     ( If this isn't a copy, Quit! )
  356.     key drop save bye ( hit key to continue )
  357.  
  358. Reopen Pocket Forth, then use the AETest stack to send 'clos' to your new copy. The Pocket Forth window will disappear. You must Quit to reopen the window.
  359. While this may not be useful, you have added a new Apple Event handler.
  360.  
  361. Errors are posted when an Apple Event sent to Pocket Forth is not handled properly. The error routine (address at "190 +md") is executed if an error occured, with the error number on the stack. "Drop" is the default handler for the error routine. Install a sample error handler:
  362.  
  363.     : AEERROR ( error.no -- ) ." Apple Event error:" . ;
  364.     ' aeerror 190 +md !  ( install error handler, no need to save this )
  365.  
  366. Send Pocket Forth an 'eval' event from the AETest stack. The error code for 'handler not installed' will be printed.
  367.  
  368.  
  369. Turnkey
  370.  
  371. In the Forth world, "turnkey" means to produce a stand alone program from the interpreter. Because most commercial Forth interpreters are proprietary, a side effect of turnkeying is that the interpreter is sealed off, and no longer available to the program's user.
  372.  
  373. For many programs, this is preferable since the interpreter can be confusing to many users. Pocket Forth can turnkey applications with or without this side effect.
  374.  
  375. The essence of the turnkey process is the assignment of new values to Pocket Forth's event and message handlers. Define a word with the correct actions, then place the address of the word in the unnamed variable used by the particular event or message. Use "save" to make the changes a permanent part of the program once it is debugged.
  376.  
  377. The button, activate and update events, idle and menu messages should be set as described in the events and menu sections.
  378.  
  379. The idle routine is run once each time through the event loop. As mentioned above the idle routine is used to defer actions set by some Apple Events. Specifically the 'odoc' routine uses the idle handler. See the AppleEvents file to see how to do that.
  380.  
  381. The start up handler is executed after everything is setup and just before the interpreter loop is entered. You can write programs that do not give the user access to the interpreter. Do this by entering an endless event loop in the start up handler. Run time structures, such as data blocks, should be created in the startup handler.
  382.  
  383. The close handler is run when the close box of the window is clicked. The default close handler calls "bye" and returns, causing the application to quit by 'falling through' to the launching call (usually the Finder).
  384.  
  385. Key down events are not ignored, rather the application is centered around getting and handling key presses. The main event loop of Pocket Forth is contained in the words "expect", "key" and "?terminal". Write an event loop for your program by embedding one of these words in a loop:
  386.  
  387.    … EXPECT …                   ( handle all events until a return is typed )
  388.    ... BEGIN  KEY .. handle key data .. AGAIN ...       ( endless event loop )
  389.    or    ... BEGIN ... ?TERMINAL UNTIL ...           ( a one shot event loop )
  390.  
  391. Run non-key events in their handler routines. Key events are handled in the event loop code. Here is the turnkey example:
  392.  
  393. ( Handler demo application )
  394. ( Show the events as they are processed )
  395. ( The idle routine should only run once a second )
  396.   variable TLAST  0 tlast !    ( hold the last value of ticks here )
  397.   : TICKS ( -- n ) 364 0 l@ ;   ( low word of 'ticks' system variable )
  398.   : ?1SEC ( -- flag ) ( true if >1 second has elapsed since last time )
  399.       ticks tlast @ - abs 60 > ;  ( is time difference > 1 sec? )
  400.   : MYIDLE ( -- ) ?1sec IF ticks tlast !  ( update tlast )
  401.         ." Idle" cr  THEN ;  ( wait 1 second between idle messages )
  402.   : MYACTIVATE ( flag -- ) IF ." Activated" ELSE ." Deactivated" THEN cr ;
  403.   : MYUPDATE ( -- ) ." Window updated" cr ;
  404.   : MYBUTTON ( -- ) ." Window clicked" cr ;
  405.   : MYKEY ( c -- ) emit space ." key pressed" cr ;
  406.   : MYCLOSE ( -- ) ." Closed" cr  bye ;
  407.   : MYSTARTUP ( -- ) ." Hi There!" cr
  408.       BEGIN key  ( "key" waits for a key press and runs event handlers )
  409.         mykey  AGAIN ;  ( Loop through the key handler indefinitely )
  410.   ' mystartup 26 +md !      ( set the open handler )
  411.   ' myclose 22 +md !         ( set the close handler )
  412.   ' myidle 20 +md !           ( set the idle handler )
  413.   ' mybutton 16 +md !       ( set the button handler )
  414.   ' myupdate 14 +md !       ( set the update handler )
  415.   ' myactivate 12 +md ! ;  ( set activate handler )
  416.   page
  417.   ( If this is not a copy, Quit!   )
  418.   ( ...Or hit a key to continue... ) key drop save bye
  419.  
  420. Once a turnkey program is finished, debugged, and all variables are initialized, save the dictionary, replacing the one stored on the disk. Then use ResEdit to change the resources such as the window title and the application's icon (as well as BNDL, FREF and signature resource) and About… item. Be sure to "save" only copies of Pocket Forth since the changes are permanent and cannot be undone.
  421.  
  422. The ReadMe application is an example of a turnkey program. Recompile ReadMe by using ResEdit to replace the DICT resource of (a copy of) ReadMe with a DICT copied from Pocket Forth. Save and close ReadMe from ResEdit. Launch ReadMe, which will open a Pocket Forth window. Load the file Reader using "open", and the ReadMe application will be rebuilt.
  423.  
  424. Versions
  425.  
  426. The Pocket Forth version number is a two part number written as: T.V. 'T' is the program type and 'V' is the version within that type. Additional numbers indicate corrections within a version. Type 0 is an application with a sixteen bit stack and subroutine threading. The current version is 0.6.
  427.  
  428. Type 1 is a desk accessory, development of which has been curtailed. Version 1.5 is the most recent DA version. If you need to continue to use the desk accessory, fix a fatal bug by pasting the following line into a copy of 1.5.
  429.  
  430.     128  ' back 17 +  c!   save  ( fix back bug )
  431.  
  432. No desk accessory is provided with this release because System 7 had made DAs redundant.
  433.  
  434. Write to the author, Chris Heilman, if you have questions or comments.
  435.          Email:           "heilman@pc.maricopa.edu"
  436.          CompuServe: [70566,1474]
  437.          AOL:              cheilman
  438.          US Mail:         PO box 8345
  439.                               Phoenix, AZ 85066-8345.
  440.  
  441. Bibliographic Notes:
  442.  
  443. (1) Barnhart, Joe,  "FORTH and the Motorola 68000", Dr. Dobbs Journal no. 83, September 1983, Peoples Computer Company.
  444.  
  445. (2) Greene, Ronald, "Faster Forth", Byte v.9 no.6, June 1984,  McGraw Hill Publishing Co.
  446.  
  447. (3) Loeliger, R. G.  Threaded Interpretive Languages, Byte Books, 1981.
  448.  
  449. (4) Fletcher, G. Yates,  "A Mini Forth for the 68000", Dr. Dobb's Journal no.123, January 1987, M&T Publishing, Inc. This article presents Flint, Forth interpreter in 68000 assembly language. Pocket Forth owes much of its structure and philosophy to Flint, and I thank Professor Fletcher and Dr. Dobb's Journal for publishing Flint.
  450.  
  451. (5) Ragsdale, William F., et al.  fig-FORTH Installation Manual, release 1,  Nov. 1980, Forth Interest Group. Includes Forth in Forth and source code for figFORTH.
  452.  
  453. (6) Derick, Mitch and Linda Baker  FORTH Encyclopedia, Second Edition, Mountain View Press, Inc.  1982. The FORTH Encyclopedia shows the definitions of fig-FORTH words.
  454.  
  455. (7) Brodie, Leo  Starting FORTH, FORTH, Inc. / Prentice Hall, 1981. The FORTH instruction manual and fun to read. You can't learn Forth without this book.
  456.  
  457. (8) Chavez, Lori,  "A Fast Forth for the 68000", Dr. Dobb's Journal no. 132, October 1987, M&T Publishing, Inc. This article describes how to implement macros.
  458.  
  459. (9) Knaster, Scott  How to write Macintosh Software, Hayden Book Co., 1986
  460.  
  461. (10) Apple Computer Inc.  Inside Macintosh, volume I through volume VI and X-Ref, Addison Wesley, 1985-1991
  462.  
  463. (11) Apple Computer Inc.  Apple Numerics Manual, Second Edition, Addison Wesley, 1988 This book describes SANE.
  464.  
  465. (12) Brodie, Leo  Thinking Forth, Prentice Hall, 1984. The elements of code reusability are clearly explained, years before it became fashionable. Fun.
  466.  
  467. (13) Little, Gary & Tim Swihart, Programming for System 7, Addison Wesley, 1991 Geared toward C but useful none-the-less.
  468.  
  469. (14) Tracy, Martin,  "Zen Floating Point", Dr. Dobb's Toolbook of Forth, volume II, M&T Publishing, 1987. Philosophical support for using floating point numbers on the stack.
  470.